#include <stdio.h>
#include <stdlib.h>

typedef double CoefSet; /* 定义多项式系数为double型 */
#define eps (1e-9)

typedef struct PolyNode *Position; /* 指针即结点位置 */
struct PolyNode {
    CoefSet coef; /* 系数 */
    int expon; /* 指数 */
    Position next; /* 线性表中下一个元素的位置 */
};
typedef Position Polynomial;

Position Attach(CoefSet coef, int expon, Position rear);
Polynomial ReadPoly();
Polynomial PolynomialAdd(Polynomial p1, Polynomial p2);

int main(void) {
    Polynomial p1, p2, p;
    Position tmp;

    p1 = ReadPoly();
    p2 = ReadPoly();
    p = PolynomialAdd(p1, p2);
    tmp = p;
    while (tmp != NULL) {
        printf("%.2f %d\n", tmp->coef, tmp->expon);
        tmp = tmp->next;
    }
    return 0;
}

/* 算法2-9：一元多项式加法运算  PolynomialAdd(p1, p2) */
Polynomial PolynomialAdd(Polynomial p1, Polynomial p2) {
    Position rear, temp;
    Polynomial p;
    CoefSet sum;

    p = (Polynomial)malloc(sizeof(struct PolyNode)); /* 创建临时空头结点 */
    rear = p; /* rear指向多项式最后一个结点，初始化指向空头结点 */
    rear->next = NULL;
    while ((p1 != NULL) && (p2 != NULL)) {
        if (p1->expon > p2->expon) { /* p1中的数据项指数较大 */
            rear = Attach(p1->coef, p1->expon, rear);
            p1 = p1->next;
        } else if (p1->expon < p2->expon) { /* p2中的数据项指数较大 */
            rear = Attach(p2->coef, p2->expon, rear);
            p2 = p2->next;
        } else { /* 两数据项指数相等 */
            sum = p1->coef + p2->coef;
            if (sum >= eps || sum <= -eps) { /* 如果和不为0 */
                rear = Attach(sum, p1->expon, rear);
            }
            p1 = p1->next;
            p2 = p2->next;
        }
    }
    /* 将未处理完的另一个多项式的所有结点依次复制到结果多项式中去 */
    while (p1 != NULL) {
        rear = Attach(p1->coef, p1->expon, rear);
        p1 = p1->next;
    }
    while (p2 != NULL) {
        rear = Attach(p2->coef, p2->expon, rear);
        p2 = p2->next;
    }
    temp = p;
    p = p->next; /* 令p指向结果多项式第一个非零项 */
    free(temp); /* 清除临时空头结点 */
    return p;
}
/* 算法2-9 结束 */

Position Attach(CoefSet coef, int expon, Position rear) {
    rear->next = (Position)malloc(sizeof(struct
                                         PolyNode)); /* 在rear后面新建一个结点 */
    rear->next->coef = coef;
    rear->next->expon = expon;
    rear->next->next = NULL;
    rear = rear->next; /* rear指向新的最后一个结点 */
    return rear;
}

Polynomial ReadPoly() {
    int i, n;
    CoefSet coef;
    int expon;
    Position rear, temp;
    Polynomial p;

    p = (Polynomial)malloc(sizeof(struct PolyNode)); /* 创建临时空头结点 */
    rear = p; /* rear指向多项式最后一个结点，初始化指向空头结点 */
    rear->next = NULL;
    scanf("%d", &n); /* 读入多项式非零项个数 */
    for (i = 0; i < n; i++) { /* 读入每个非零项，按指数递减 */
        scanf("%lf %d", &coef, &expon);
        rear = Attach(coef, expon, rear); /* 新增非零项贴到多项式尾部 */
    }
    temp = p;
    p = p->next; /* 令p指向结果多项式第一个非零项 */
    free(temp); /* 清除临时空头结点 */
    return p;
}